﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

/// <summary>
/// 普通单例,会自动初始化对象
/// </summary>
/// <typeparam name="T">单例类</typeparam>
public class SingletonAuto<T> where T : SingletonAuto<T>, new()
{
    private static T _instance;
    public static T me
    {
        get
        {
            if (_instance == null)
            {
                _instance = new T();
            }
            return _instance;
        }
    }
    public static T TryGetInstance()
    {
        return _instance;
    }
    public static void Destroy()
    {
        if (_instance != null)
        {
            _instance.OnDestroy();
            _instance = null;
        }
    }
    public SingletonAuto()
    {
        if (_instance != null)
        {
            throw new Exception(typeof(T).ToString() + "constructed twice!");
        }
        _instance = (T)this;
    }
    /// <summary>
    /// 清理时的处理
    /// </summary>
    protected virtual void OnDestroy()
    {
    }
}
